# -*- coding: utf-8 -*-
"""
-------------------------------------------------
Project Name: luffcity study project
File Name: client_interface.py
Author: kij
Create Date: 2021/3/20
-------------------------------------------------
"""
import os
import json
from modle.client_modle import Clent


def cd_dir_impl(user, msg):
	"""
	跳转文件夹，切换路径,返回切换后的路径
	:return:
	"""
	print(msg.get('message'))
	user.context_path = msg.get('context_path')


def _mkdir_impl(user, msg):
	"""
	跳转文件夹，切换路径,返回切换后的路径
	:return:
	"""
	print(msg.get('message'))


def ls_dir_impl(user, msg):
	"""
	根据输入命令，然后返回文件夹进行显示
	:return:
	"""
	print(msg.get('message'))


def upload_impl(user, msg):
	"""
	上传文件，上传完成文件返回上传状态信息，是否上传完成
	:return:
	"""
	user.upload(msg)


def unfinished_file_check(user):
	"""检查shelve db ，把为正常传完的文件列表打印，按用户的指令决定是否重传"""

	if list(user.shelve_obj.keys()):
		for index, abs_file in enumerate(user.shelve_obj.keys(),start=1):
			# 已经下载了的文件大小
			print(user.shelve_obj[abs_file][1])
			received_file_size = os.path.getsize(user.shelve_obj[abs_file][1])
			print(
				"%s. %s    %s    %s   %s" % (
					index, abs_file, user.shelve_obj[abs_file][0],
					received_file_size, received_file_size / user.shelve_obj[abs_file][0] * 100
				))
		while True:
			choice = input("选择的未下载的文件:").strip()
			if not choice: continue
			if choice.isdecimal():
				choice = int(choice)
				if choice >= 0 and choice <= index:
					selected_file = list(user.shelve_obj.keys())[choice-1]
					# 拿到已经接收的文件大小
					already_received_size = os.path.getsize(user.shelve_obj[selected_file][1])

					func_switch(user, ['re_get', selected_file, already_received_size])
					break


def download_impl(user, msg):
	"""
	下载方法，下载文件，返回下载完成信息
	:return:
	"""
	user.download(msg)
	print()


def re_get_impl(user, msg):
	"""
	下载方法，下载文件，返回下载完成信息
	:return:
	"""
	print(msg)
	user.re_get_file(msg)
	print()


def logon_impl(msg, conn):
	"""
	登录方法，登录成功后拿到根目录路径并显示，还有用户信息
	:return:
	"""
	client = Clent(conn, msg[0], msg[1])
	client.logon()
	unfinished_file_check(client)
	return client


def register_impl(msg, conn):
	"""
	登录方法，登录成功后拿到根目录路径并显示，还有用户信息
	:return:
	"""
	res = Clent.register(conn, msg[0], msg[1])
	res_dict = json.loads(res.decode('utf-8'))
	print(res_dict)
	if res_dict.get('type') == 'register':
		return '注册成功,请登录'
	else:
		return '注册失败'


fun_dict = {
	'logon': logon_impl,  # 登录
	'get': download_impl,  # 下载
	'put': upload_impl,  # 上传
	'ls': ls_dir_impl,  # 显示文件加目录
	'dir': ls_dir_impl,  # 显示文件加目录
	'cd': cd_dir_impl,  # 切换文件加目录
	'mkdir': _mkdir_impl,  # 新建文件夹
	're_get': re_get_impl,  # 下载

}


def func_switch(user, msg):
	# 发送数据并接受到服务器返回的结果然后进行判断
	res = user.send_func2server(msg)
	res_dict = json.loads(res.decode('utf-8'))
	if res_dict['type'] not in fun_dict:
		print(res_dict['message'])
	else:
		fun_dict[res_dict['type']](user, res_dict)
	return user
